﻿using System;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using XamlingCore.Infrastructure.Callbacks;
using XamlingCore.SL.Controls.ContentTemplate.Interfaces;

namespace XamlingCore.SL.Controls.Content
{
    [TemplateVisualState(GroupName="ContentStates", Name="NoContent")]
    [TemplateVisualState(GroupName = "ContentStates", Name = "Content")]
    public class XSelectableContentTemplateContentControl : XContentControl
    {
        private static QueueCallback queue = new QueueCallback(TimeSpan.FromSeconds(.7));
        private bool templateApplied;
        public XSelectableContentTemplateContentControl()
        {
            //updateStates(false);
        }

        void updateStates(bool trans)
        {
            
        }

        public IContentTemplateSelector TemplateSelector
        {
            get { return (IContentTemplateSelector)GetValue(TemplateSelectorProperty); }
            set { SetValue(TemplateSelectorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TemplateSelector.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TemplateSelectorProperty =
            DependencyProperty.Register("TemplateSelector", typeof(IContentTemplateSelector), typeof(XSelectableContentTemplateContentControl), null);

        private object updateToContent;

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            ApplyTemplate();
            
            if (newContent == updateToContent && newContent!=null)
            {
                Debug.WriteLine("ContentChanged");
                base.OnContentChanged(oldContent, newContent);
                return;
            }

            if (newContent != null && newContent != oldContent && newContent != updateToContent)
            {
                Debug.WriteLine("Update Content");
                updateToContent = newContent;
                queue.Add(() =>
                {
                    var template = TemplateSelector.SelectTemplate(updateToContent);
                    ContentTemplate = template;
                    Content = updateToContent;
                    //base.OnContentChanged(oldContent, newContent);
                    VisualStateManager.GoToState(this, "Content", true);
                    //updateStates(true);
                });
                Content = null;

            }
            else
            {
                Content = null;
            }
            


        }
    }
}
